﻿//-----------------------------------------------------------------------
// <Copyright>
// * Copyright (C) 2022 RuYiAdmin All Rights Reserved
// </Copyright>
//-----------------------------------------------------------------------

using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using RuYiAdmin.Net.CommonInfrastructure.Classes;
using RuYiAdmin.Net.CommonInfrastructure.Configurations;
using RuYiAdmin.Net.CommonInfrastructure.Constants.Framework;
using RuYiAdmin.Net.CommonInfrastructure.Constants.System;
using RuYiAdmin.Net.CommonInfrastructure.Enums.Business;
using RuYiAdmin.Net.CommonInfrastructure.Enums.Framework;
using RuYiAdmin.Net.CommonInfrastructure.Exceptions.Framework;
using RuYiAdmin.Net.CommonInfrastructure.Extensions.Business;
using RuYiAdmin.Net.CommonInfrastructure.Models;
using RuYiAdmin.Net.CommonInfrastructure.Utilities.Contexts;
using RuYiAdmin.Net.CommonInfrastructure.Utilities.Utils;
using RuYiAdmin.Net.EntityDataModel.DataTransformationModel.SystemModel;
using RuYiAdmin.Net.EntityDataModel.EntityModel.SystemModel;
using RuYiAdmin.Net.EntityDataModel.SessionScope;
using RuYiAdmin.Net.ServiceLayer.BusinessService.Interface.FrameworkInterface;
using RuYiAdmin.Net.ServiceLayer.BusinessService.Interface.SystemInterface;
using RuYiAdmin.Net.WebApi.RuYiAdminCode.RuYiAdminAnnotation;
using RuYiAdmin.Net.WebApi.RuYiAdminCode.RuYiAdminBase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RuYiAdmin.Net.WebApi.RuYiAdminController.SystemController
{
    /// <summary>
    /// 用户管理控制器
    /// </summary>
    public class SysUserManagementController : RuYiAdminBaseController<SysUser>
    {
        #region 属性及构造函数

        /// <summary>
        /// 用户接口实例
        /// </summary>
        private readonly ISysUserService UserService;

        /// <summary>
        /// 机构与用户接口实例
        /// </summary>
        private readonly ISysOrgUserService OrgUserService;

        /// <summary>
        /// AutoMapper实例
        /// </summary>
        private readonly IMapper AutoMapper;

        /// <summary>
        /// Redis接口实例
        /// </summary>
        private readonly IRedisService RedisService;

        /// <summary>
        /// ActiveMQ接口实例
        /// </summary>
        private readonly IMQService MQService;

        /// <summary>
        /// 导入配置服务接口
        /// </summary>
        private readonly ISysImportConfigService ImportConfigService;

        /// <summary>
        /// 机构服务接口
        /// </summary>
        private readonly ISysOrganizationService OrganizationService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="UserService"></param>
        /// <param name="OrgUserService"></param>
        /// <param name="AutoMapper"></param>
        /// <param name="RedisService"></param>
        /// <param name="MQService"></param>
        /// <param name="ImportConfigService"></param>
        /// <param name="OrganizationService"></param>
        public SysUserManagementController(ISysUserService UserService,
                                           ISysOrgUserService OrgUserService,
                                           IMapper AutoMapper,
                                           IRedisService RedisService,
                                           IMQService MQService,
                                           ISysImportConfigService ImportConfigService,
                                           ISysOrganizationService OrganizationService) : base(UserService)
        {
            this.UserService = UserService;
            this.OrgUserService = OrgUserService;
            this.AutoMapper = AutoMapper;
            this.RedisService = RedisService;
            this.MQService = MQService;
            this.ImportConfigService = ImportConfigService;
            this.OrganizationService = OrganizationService;
        }

        #endregion

        #region 查询用户列表

        /// <summary>
        /// 查询用户列表
        /// </summary>
        /// <param name="searchCondition">查询条件</param>
        /// <returns>ActionResponseResult</returns>
        [HttpPost]
        [Log(OperationType.QueryList)]
        [Permission("user:query:list")]
        public async Task<IActionResult> Post(SearchCondition searchCondition)
        {
            if (searchCondition.SearchItems.Count.Equals(0))
            {
                searchCondition.SearchItems = new List<SearchItem>();
                searchCondition.SearchItems.Add(new SearchItem()
                {
                    Field = "OrgId",
                    DataType = DataType.Guid,
                    SearchMethod = SearchMethod.Equal,
                    Value = RuYiSessionContext.GetUserOrgId(this.HttpContext)
                });
            }

            var users = await this.RedisService.GetAsync<List<SysUserDTO>>(RuYiGlobalConfig.SystemCacheConfig.UserCacheName);
            users = users.AsQueryable().Where(searchCondition.ConvertToLamdaExpression<SysUserDTO>()).ToList();

            if (!string.IsNullOrEmpty(searchCondition.Sort))
            {
                users = users.Sort(searchCondition.Sort);
            }

            int count = users.Count;
            users = users.Skip(searchCondition.PageIndex * searchCondition.PageSize).Take(searchCondition.PageSize).ToList();

            var actionResponseResult = QueryResponseResult<SysUserDTO>.OK(count, users);
            return Ok(actionResponseResult);
        }

        #endregion

        #region 查询用户信息

        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <returns>ActionResponseResult</returns>
        [HttpGet("{userId}")]
        [Log(OperationType.QueryEntity)]
        [Permission("user:query:list")]
        public async Task<IActionResult> GetById(Guid userId)
        {
            var users = await this.RedisService.GetAsync<List<SysUserDTO>>(RuYiGlobalConfig.SystemCacheConfig.UserCacheName);
            var actionResponseResult = ActionResponseResult.OK(users.Where(t => t.Id == userId).FirstOrDefault());
            return Ok(actionResponseResult);
        }

        #endregion

        #region 用户登录名检测

        /// <summary>
        /// 用户登录名检测
        /// </summary>
        /// <param name="logonName">用户登录名</param>
        /// <returns>ActionResponseResult</returns>
        [HttpGet("{logonName}")]
        [Log(OperationType.QueryEntity)]
        [Permission("user:add:entity")]
        public async Task<IActionResult> IsExistedLogonName(string logonName)
        {
            var actionResponseResult = new ActionResponseResult();
            actionResponseResult.HttpStatusCode = HttpStatusCode.OK;
            actionResponseResult.Message = new string("OK");

            var users = (List<SysUser>)(await this.UserService.GetListAsync()).Object;
            //var users = await this.this.RedisService.GetAsync<List<SysUserDTO>>(RuYiAdminGlobalContext.SystemCacheConfig.UserCacheName);
            var user = users.Where(t => t.LogonName.Equals(logonName)).FirstOrDefault();
            if (user != null)
            {
                actionResponseResult.Object = true;
            }
            else
            {
                actionResponseResult.Object = false;
            }

            return Ok(actionResponseResult);
        }

        #endregion

        #region 新增用户信息

        /// <summary>
        /// 新增用户信息
        /// </summary>
        /// <param name="userDTO">用户对象</param>
        /// <returns>ActionResponseResult</returns>
        [HttpPost]
        [Log(OperationType.AddEntity)]
        [Permission("user:add:entity")]
        public async Task<IActionResult> Add([FromBody] SysUserDTO userDTO)
        {
            var orgId = userDTO.OrgId;
            var orgName = userDTO.OrgName;

            var defaultPassword = RuYiGlobalConfig.SystemConfig.DefaultPassword;
            var aesKey = RuYiGlobalConfig.SystemConfig.AesKey;

            userDTO.Salt = Guid.NewGuid();
            userDTO.Password = RuYiAesUtil.Encrypt(defaultPassword + userDTO.Salt, aesKey);

            //DTO TO POCO
            var user = this.AutoMapper.Map<SysUser>(userDTO);
            //新增用户
            await this.UserService.AddAsync(user);

            //用户与机构关联
            var orgUser = new SysOrgUser();
            orgUser.OrgId = orgId;
            orgUser.UserId = user.Id;
            //新增机构与用户关系
            await this.OrgUserService.AddAsync(orgUser);

            #region 数据一致性维护

            userDTO = this.AutoMapper.Map<SysUserDTO>(user);
            userDTO.OrgId = orgId;
            userDTO.OrgName = orgName;

            var users = await this.RedisService.GetAsync<List<SysUserDTO>>(RuYiGlobalConfig.SystemCacheConfig.UserCacheName);
            users.Add(userDTO);
            await this.RedisService.SetAsync(RuYiGlobalConfig.SystemCacheConfig.UserCacheName, users, -1);

            #endregion

            var actionResponseResult = ActionResponseResult.OK(userDTO);
            return Ok(actionResponseResult);
        }

        #endregion

        #region 编辑用户信息

        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <param name="userDTO">用户对象</param>
        /// <returns>ActionResponseResult</returns>
        [HttpPut]
        [Log(OperationType.EditEntity)]
        [Permission("user:edit:entity")]
        public async Task<IActionResult> Put([FromBody] SysUserDTO userDTO)
        {
            var task = await this.UserService.GetByIdAsync(userDTO.Id);
            var origin = (SysUser)task.Object;

            userDTO.Password = RuYiRsaUtil.PemDecrypt(userDTO.Password, RuYiGlobalConfig.SystemConfig.RsaPrivateKey);
            if (!origin.Password.Equals(userDTO.Password))
            {
                userDTO.Salt = Guid.NewGuid();
                userDTO.Password = RuYiAesUtil.Encrypt(userDTO.Password + userDTO.Salt, RuYiGlobalConfig.SystemConfig.AesKey);
            }

            var orgId = userDTO.OrgId;
            var orgName = userDTO.OrgName;

            //DTO TO POCO
            var user = this.AutoMapper.Map<SysUser>(userDTO);
            var actionResponseResult = await this.UserService.UpdateAsync(user);

            if (user.IsEnabled.Equals(0))
            {
                #region 强制禁用用户下线

                var pattern = $"{RuYiGlobalConfig.RedisConfig.Pattern + user.Id + "_"}*";
                var keys = this.RedisService.PatternSearch(pattern);
                if (keys.Count > 0)
                {
                    foreach (var item in keys)
                    {
                        await this.RedisService.DeleteAsync(new string[] { item.ToString() });
                    }
                }

                var msg = new SystemMessage();
                msg.Message = Keywords.FORCELOGOUT;
                msg.MessageType = MessageType.ForceLogout;
                msg.Object = user;

                this.MQService.SendTopic(JsonConvert.SerializeObject(msg));

                #endregion
            }

            #region 数据一致性维护

            userDTO = this.AutoMapper.Map<SysUserDTO>(user);
            userDTO.OrgId = orgId;
            userDTO.OrgName = orgName;

            //获取用户缓存
            var users = await this.RedisService.GetAsync<List<SysUserDTO>>(RuYiGlobalConfig.SystemCacheConfig.UserCacheName);

            //删除就数据
            var old = users.Where(t => t.Id == userDTO.Id).FirstOrDefault();
            users.Remove(old);

            //添加新数据
            users.Add(userDTO);

            //更新用户缓存
            await this.RedisService.SetAsync(RuYiGlobalConfig.SystemCacheConfig.UserCacheName, users, -1);

            //更新机构的管理人姓名
            if (origin.DisplayName != userDTO.DisplayName)
            {
                //获取机构缓存
                var orgs = await this.RedisService.GetAsync<List<SysOrganizationDTO>>(RuYiGlobalConfig.SystemCacheConfig.OrgCacheName);
                var subs = orgs.Where(t => t.Leader != null && t.Leader == userDTO.Id).ToList();

                foreach (var item in subs)
                {
                    //删除旧数据
                    var oldOrg = item;
                    orgs.Remove(oldOrg);

                    //更新机构管理人姓名
                    item.LeaderName = userDTO.DisplayName;
                    orgs.Add(item);
                }

                //更新机构缓存
                await this.RedisService.SetAsync(RuYiGlobalConfig.SystemCacheConfig.OrgCacheName, orgs, -1);
            }

            #endregion

            return Ok(actionResponseResult);
        }

        #endregion

        #region 删除用户信息

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <returns>ActionResponseResult</returns>
        [HttpDelete("{userId}")]
        [Permission("user:del:entities")]
        [Log(OperationType.DeleteEntity)]
        public async Task<IActionResult> Delete(Guid userId)
        {
            var actionResponseResult = await this.UserService.DeleteEntity(userId);

            #region 数据一致性维护

            var users = await this.RedisService.GetAsync<List<SysUserDTO>>(RuYiGlobalConfig.SystemCacheConfig.UserCacheName);
            var user = users.Where(t => t.Id == userId).FirstOrDefault();
            users.Remove(user);
            await this.RedisService.SetAsync(RuYiGlobalConfig.SystemCacheConfig.UserCacheName, users, -1);

            #endregion

            #region 强制用户下线

            var pattern = $"{RuYiGlobalConfig.RedisConfig.Pattern + user.Id + "_"}*";
            var keys = this.RedisService.PatternSearch(pattern);
            if (keys.Count > 0)
            {
                foreach (var item in keys)
                {
                    await this.RedisService.DeleteAsync(new string[] { item.ToString() });
                }
            }

            var msg = new SystemMessage();
            msg.Message = Keywords.FORCELOGOUT;
            msg.MessageType = MessageType.ForceLogout;
            msg.Object = user;

            this.MQService.SendTopic(JsonConvert.SerializeObject(msg));

            #endregion

            return Ok(actionResponseResult);
        }

        #endregion

        #region 批量删除用户

        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="ids">编号数组</param>
        /// <returns>ActionResponseResult</returns>
        [HttpDelete("{ids}")]
        [Log(OperationType.DeleteEntity)]
        [Permission("user:del:entities")]
        public async Task<IActionResult> DeleteRange(string ids)
        {
            var actionResponseResult = await this.UserService.DeleteEntities(ids);

            #region 数据一致性维护

            var users = await this.RedisService.GetAsync<List<SysUserDTO>>(RuYiGlobalConfig.SystemCacheConfig.UserCacheName);
            var array = RuYiStringUtil.GetGuids(ids);

            foreach (var item in array)
            {
                var user = users.Where(t => t.Id == item).FirstOrDefault();
                users.Remove(user);

                #region 强制用户下线

                var pattern = $"{RuYiGlobalConfig.RedisConfig.Pattern + user.Id + "_"}*";
                var keys = this.RedisService.PatternSearch(pattern);
                if (keys.Count > 0)
                {
                    foreach (var key in keys)
                    {
                        await this.RedisService.DeleteAsync(new string[] { key.ToString() });
                    }
                }

                var msg = new SystemMessage();
                msg.Message = Keywords.FORCELOGOUT;
                msg.MessageType = MessageType.ForceLogout;
                msg.Object = user;

                this.MQService.SendTopic(JsonConvert.SerializeObject(msg));

                #endregion
            }

            await this.RedisService.SetAsync(RuYiGlobalConfig.SystemCacheConfig.UserCacheName, users, -1);

            #endregion

            return Ok(actionResponseResult);
        }

        #endregion

        #region 用户登录系统

        /// <summary>
        /// 用户登录系统
        /// </summary>
        /// <param name="loginDTO">登录信息</param>
        /// <returns>ActionResponseResult</returns>
        [HttpPost]
        [AllowAnonymous]
        //[Log(OperationType.Logon)]
        public async Task<IActionResult> Logon([FromBody] LoginDTO loginDTO)
        {
            var actionResponseResult = await this.UserService.Logon(loginDTO);
            return Ok(actionResponseResult);
        }

        #endregion

        #region 用户退出登录

        /// <summary>
        /// 用户退出登录
        /// </summary>
        /// <param name="token">token</param>
        /// <returns>ActionResponseResult</returns>
        [HttpGet("{token}")]
        //[Log(OperationType.Logout)]
        public async Task<IActionResult> Logout(string token)
        {
            var actionResponseResult = await this.UserService.Logout(token);
            return Ok(actionResponseResult);
        }

        #endregion

        #region 强制用户退出

        /// <summary>
        /// 强制用户退出
        /// </summary>
        /// <param name="token">token</param>
        /// <returns>ActionResponseResult</returns>
        [HttpGet("{token}")]
        [Log(OperationType.ForceLogout)]
        public async Task<IActionResult> ForceLogout(string token)
        {
            //获取用户
            var user = await this.RedisService.GetAsync<SysUserDTO>(token);

            //注销用户
            var actionResponseResult = await this.UserService.Logout(token, OperationType.ForceLogout, $"{user.DisplayName + "/" + user.LogonName}被超级管理员强制下线");

            #region 强制用户下线

            var msg = new SystemMessage();
            msg.Message = Keywords.FORCELOGOUT;
            msg.MessageType = MessageType.ForceLogout;
            msg.Object = user;

            this.MQService.SendTopic(JsonConvert.SerializeObject(msg));

            #endregion

            return Ok(actionResponseResult);
        }

        #endregion

        #region 按机构获取用户

        /// <summary>
        /// 按机构获取用户
        /// </summary>
        /// <param name="orgId">机构编号</param>
        /// <returns>ActionResponseResult</returns>
        [HttpGet("{orgId}")]
        [Log(OperationType.QueryList)]
        public async Task<IActionResult> GetUserByOrgId(Guid orgId)
        {
            var users = await this.RedisService.GetAsync<List<SysUserDTO>>(RuYiGlobalConfig.SystemCacheConfig.UserCacheName);
            users = users.Where(t => t.OrgId == orgId).ToList();

            var actionResponseResult = QueryResponseResult<SysUserDTO>.Success(users.Count, users);
            return Ok(actionResponseResult);
        }

        #endregion

        #region 更新用户密码

        /// <summary>
        /// 更新用户密码
        /// </summary>
        /// <param name="data">参数</param>
        /// <returns>ActionResponseResult</returns>
        [HttpPost]
        [Log(OperationType.UpdatePassword)]
        public async Task<IActionResult> UpdatePassword([FromBody] PasswordDTO data)
        {
            var actionResponseResult = await this.UserService.UpdatePassword(data);
            return Ok(actionResponseResult);
        }

        #endregion

        #region 获取在线用户

        /// <summary>
        /// 获取在线用户
        /// </summary>
        /// <returns>ActionResponseResult</returns>
        [HttpGet]
        [Log(OperationType.QueryList)]
        [Permission("user:query:onlineUsers")]
        public async Task<IActionResult> GetOnlineUsers()
        {
            var actionResponseResult = await this.UserService.GetOnlineUsers();
            return Ok(actionResponseResult);
        }

        #endregion

        #region 导入用户信息

        /// <summary>
        /// 导入用户信息
        /// </summary>
        /// <param name="file">excel文件</param>
        /// <param name="orgId">moduleId</param>
        /// <returns>ActionResponseResult</returns>
        [HttpPost]
        [Log(OperationType.ImportData)]
        [Permission("user:import:entities")]
        public async Task<IActionResult> Import([FromForm] IFormFile file, Guid orgId)
        {
            var actionResponseResult = new ActionResponseResult();

            if (file != null)
            {
                #region 常规合法性校验

                //获取文件拓展名
                var extension = Path.GetExtension(file.FileName);
                //文件保存路径
                var filePath = RuYiFileContext.SaveFormFile(file);

                var configDTO = ImportConfigService.GetImportConfig("UserImportConfig");
                if (configDTO == null)
                {
                    throw new RuYiAdminCustomException(WarnningMessage.ImportConfigNotFindMessage);
                }

                configDTO.ExcelPath = filePath;
                //常规合法性校验
                var errorCount = configDTO.ValidationDetecting();

                #endregion

                if (errorCount > 0)
                {
                    #region 常规校验出不合规项

                    actionResponseResult.Object = errorCount;
                    actionResponseResult.Message = configDTO.ExcelPath.Replace(extension, "").Split('/')[1];

                    #endregion
                }
                else
                {
                    #region 常规业务性校验

                    var users = (List<SysUser>)(await this.UserService.GetListAsync()).Object;
                    //users = users.Where(t => t.IsDel == (int)DeletionType.Undeleted).ToList();

                    var xlxStream = new FileStream(configDTO.ExcelPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    var workbook = new HSSFWorkbook(xlxStream);
                    var worksheet = workbook.GetSheetAt(0);

                    for (var i = configDTO.StartRow; i <= worksheet.LastRowNum; i++)
                    {
                        var value = worksheet.GetRow(i).GetCell(2).GetCellValue().Trim();
                        if (!string.IsNullOrEmpty(value))
                        {
                            var user = users.Where(t => t.LogonName.Equals(value)).FirstOrDefault();
                            if (user != null)
                            {
                                errorCount++;
                                worksheet.SetCellComment(i, 2, "用户已存在！");
                            }
                        }
                    }

                    #endregion

                    if (errorCount > 0)
                    {
                        #region 业务校验出不合规项

                        var xlxPath = configDTO.ExcelPath;
                        configDTO.ExcelPath = workbook.SaveAsXlx(xlxPath);

                        xlxStream.Close();
                        System.IO.File.Delete(xlxPath);

                        actionResponseResult.Object = errorCount;
                        actionResponseResult.Message = configDTO.ExcelPath.Replace(extension, "").Split('/')[1];

                        #endregion
                    }
                    else
                    {
                        #region 执行业务导入

                        var userList = await this.RedisService.GetAsync<List<SysUserDTO>>(RuYiGlobalConfig.SystemCacheConfig.UserCacheName);

                        var org = (SysOrganization)(await OrganizationService.GetByIdAsync(orgId)).Object;
                        var defaultPassword = RuYiGlobalConfig.SystemConfig.DefaultPassword;
                        var aesKey = RuYiGlobalConfig.SystemConfig.AesKey;

                        //映射工作簿列与对象属性之间的关系
                        Dictionary<string, string> dictionary = new Dictionary<string, string>();
                        dictionary.Add("用户姓名", "DisplayName");
                        dictionary.Add("登录账号", "LogonName");
                        dictionary.Add("性别", "Sex");
                        dictionary.Add("手机号", "MobilePhone");
                        dictionary.Add("座机号", "Telephone");
                        dictionary.Add("电子邮件", "Email");

                        var list = worksheet.ToList<SysUser>(configDTO.StartRow, configDTO.StartColumn, dictionary);
                        foreach (var user in list)
                        {
                            //开始事务
                            var result = await this.UserService.UseTransactionAsync(async () =>
                            {
                                user.Salt = Guid.NewGuid();
                                user.Password = RuYiAesUtil.Encrypt(defaultPassword + user.Salt, aesKey);
                                user.IsEnabled = (int)YesNo.YES;
                                //新增用户
                                await this.UserService.AddAsync(user, true, false);

                                //用户与机构关联
                                var orgUser = new SysOrgUser();
                                orgUser.OrgId = org.Id;
                                orgUser.UserId = user.Id;
                                //新增机构与用户关系
                                await this.OrgUserService.AddAsync(orgUser, true, false);
                            });

                            if (result.IsSuccess)
                            {
                                #region 数据一致性维护

                                var userDTO = this.AutoMapper.Map<SysUserDTO>(user);
                                userDTO.OrgId = org.Id;
                                userDTO.OrgName = org.OrgName;

                                userList.Add(userDTO);

                                #endregion
                            }
                        }

                        await this.RedisService.SetAsync(RuYiGlobalConfig.SystemCacheConfig.UserCacheName, userList, -1);

                        workbook.Close();
                        xlxStream.Close();

                        #endregion
                    }
                }

                actionResponseResult.HttpStatusCode = HttpStatusCode.OK;
            }
            else
            {
                actionResponseResult.HttpStatusCode = HttpStatusCode.NoContent;
                actionResponseResult.Message = new string("NoContent");
            }

            return Ok(actionResponseResult);
        }

        #endregion

        #region 导出用户信息

        /// <summary>
        /// 导出用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Log(OperationType.ExportData)]
        [Permission("user:import:entities")]
        public async Task<IActionResult> ExportExcel()
        {
            var users = await this.RedisService.GetAsync<List<SysUserDTO>>(RuYiGlobalConfig.SystemCacheConfig.UserCacheName);

            //剔除超级用户
            var super = users.Where(t => t.IsSupperAdmin == (int)YesNo.YES && t.OrgId == Guid.Empty).ToList();
            users.RemoveRange(super);

            var currentUser = RuYiSessionContext.GetCurrentUserInfo(this.HttpContext);
            if (currentUser.IsSupperAdmin == (int)YesNo.NO)
            {
                //获取用户机构编号
                var orgId = RuYiSessionContext.GetUserOrgId(this.HttpContext);
                users = users.Where(r => r.OrgId == orgId).ToList();
                users = users.OrderBy(t => t.SerialNumber).ToList();
            }

            var stream = users.Export().ToStream();
            stream.Position = 0;

            return File(stream, "application/octet-stream", "用户信息.xls");
        }

        #endregion
    }
}
